package com.shop.servlet;

import com.shop.bean.Product;
import com.shop.dao.ProductDAO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/MainServlet")
public class MainServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String method = request.getParameter("method");
        if (method == null) method = "index";

        switch (method) {
            case "index":
                showIndex(request, response);
                break;
            case "showProduct":
                showProduct(request, response);
                break;
            default:
                showIndex(request, response);
        }
    }

    // 显示首页
    private void showIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }

    // 关键：游客查看商品时，加载未售出商品（上架/冻结）
    private void showProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductDAO productDAO = new ProductDAO();
        Product product = productDAO.getActiveProduct(); // 调用修改后的方法
        request.setAttribute("product", product);
        request.getRequestDispatcher("product.jsp").forward(request, response);
    }
}